﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ModelLayer.Appointments;
using System.Data;
using ModelLayer;
using System.IO;

namespace DataAccessLayer.Appointments
{
    public class AppointmentDataAccess
    {
        MedAgendaEntities entities = new MedAgendaEntities();

        public void CancelVisit(string AccessionNumber, string CancelingPurpose, string CancelReason)
        {
            var order = (from o in entities.Order_
                         where o.AccessionNumber_.Equals(AccessionNumber)
                         select o).FirstOrDefault();
            order.OrderStatusEnum_Code_ = "CA";
            order.CancelComment_ = CancelingPurpose;
            order.OrderCancelReasonEnum__Code_ = CancelReason;

            var visit = (from v in entities.Visit_
                         where v.VisitNumberId_.Equals(AccessionNumber)
                         select v).FirstOrDefault();
            visit.VisitStatusEnum__Code_ = "CX";

            entities.SaveChanges();
        }

        public string GetNameByDescription(string description)
        {
            //GestorBD.Query = "SELECT Name_ FROM Location_ WHERE Description_='" + description + "'";
            //return GestorBD.EjecutarSentencia().Rows[0].ItemArray[0].ToString();
            return "";
        }

        public void InsertNewVisit(Visit visit)
        {
            Visit_ v = new Visit_();
            v.OID_ = Guid.NewGuid();
            v.Version_ = 1;
            v.Patient__OID_ = visit.PatientOID;
            v.VisitNumberId_ = visit.VisitNumberId;
            v.VisitStatusEnum__Code_ = "PD";
            v.IsAppointment_ = visit.IsAppointment;
            v.AdmitTime_ = visit.AdmitTime;
            v.DischargeTime_ = visit.DischargeTime;
            entities.Visit_.AddObject(v);

            Order_ o = new Order_();
            o.OID_ = Guid.NewGuid();
            o.Version_ = 1;
            o.Patient__OID_ = visit.PatientOID;
            o.Visit__OID_ = v.OID_;
            o.AccessionNumber_ = visit.AccessionNumber;
            o.EnteredTime_ = visit.AdmitTime;
            o.OrderPriorityEnum__Code_ = "R";
            o.OrderStatusEnum_Code_ = "SC";
            o.ReasonForStudy_ = visit.Purpose;
            entities.Order_.AddObject(o);

            string templatePath = Path.Combine(Directory.GetCurrentDirectory(), "template.rtf");
            Procedure_ p = new Procedure_();
            p.OID_ = Guid.NewGuid();
            p.VisitDate_ = visit.AdmitTime;
            p.Order__OID_ = o.OID_;
            using (StreamReader reader = new StreamReader(templatePath))
            {
                 p.Description_ = reader.ReadToEnd();
            }
            entities.Procedure_.AddObject(p);
            entities.SaveChanges();
        }

        public void ModifyAppointment(string accessionNumber, Visit visit)
        {
            Visit_ visit_ = (from vi in entities.Visit_
                             where vi.VisitNumberId_.Equals(accessionNumber)
                             select vi).FirstOrDefault();
            Order_ order_ = (from o in entities.Order_
                             where o.AccessionNumber_.Equals(accessionNumber)
                             select o).FirstOrDefault();

            visit_.Patient__OID_ = visit.PatientOID;
            visit_.AdmitTime_ = visit.AdmitTime;
            visit_.DischargeTime_ = visit.DischargeTime;
            visit_.IsAppointment_ = visit.IsAppointment;

            order_.Patient__OID_ = visit.PatientOID;
            order_.EnteredTime_ = visit.AdmitTime;
            order_.ReasonForStudy_ = visit.Purpose;

            entities.SaveChanges();
        }

        public List<VisitModelView> SelectAppointments(DateTime fromDate, DateTime toDate)
        {
            fromDate = fromDate.Date;
            toDate = toDate.AddDays(1).Date;
            //string fro = fromDate.Year.ToString() + "-" + fromDate.Month.ToString() + "-" + fromDate.Day.ToString();
            //string t = toDate.Year.ToString() + "-" + toDate.Month.ToString() + "-" + toDate.Day.ToString();

            var appointments = from v in entities.Visit_
                               from o in entities.Order_
                               from pp in entities.PatientProfile_
                               where v.OID_.Equals(o.Visit__OID_)
                               && pp.Patient__OID_.Equals(v.Patient__OID_)
                               && v.AdmitTime_ <= toDate && v.DischargeTime_ > fromDate
                               select new
                               {
                                   patientOID = v.Patient__OID_,
                                   visitNumberId = v.VisitNumberId_,
                                   visitStatus = v.VisitStatusEnum_.Value_,
                                   familyName = pp.FamilyName_,
                                   givenName = pp.GivenName_,
                                   middleName = pp.MiddleName_,
                                   mrnId = pp.MrnId_,
                                   orderPriority = o.OrderPriorityEnum_.Value_,
                                   admitTime = v.AdmitTime_,
                                   dischargeTime = v.DischargeTime_,
                                   purpose = o.ReasonForStudy_,
                                   birthDate = pp.DateOfBirth_,
                                   mobile = pp.PatientProfileTelephoneNumber_.Where(x => x.PatientProfile__OID_.Equals(pp.OID_) && x.TelephoneEquipmentEnum__Code_.Equals("CP")).FirstOrDefault().Number_,
                                   telephone = pp.PatientProfileTelephoneNumber_.Where(x => x.PatientProfile__OID_.Equals(pp.OID_) && x.TelephoneEquipmentEnum__Code_.Equals("PH")).FirstOrDefault().Number_,
                                   isAppointment = v.IsAppointment_
                               };

            List<VisitModelView> visitArray = new List<VisitModelView>();
            foreach (var item in appointments)
            {
                VisitModelView visitView = new VisitModelView();
                visitView.PatientOID = item.patientOID;
                visitView.AccessionNumber = item.visitNumberId;
                visitView.Status = item.visitStatus;
                visitView.FamilyName = item.familyName;
                visitView.MrnID = item.mrnId;
                visitView.MiddleName = item.middleName;
                visitView.GivenName = item.givenName;
                visitView.Priority = item.orderPriority;
                visitView.AdmitTime = (DateTime)item.admitTime;
                visitView.DischargeTime = (DateTime)item.dischargeTime;
                visitView.ReasonForStudy = item.purpose;
                visitView.DateOfBirth = (DateTime)item.birthDate;
                visitView.Telephone = item.telephone;
                visitView.MobileNumber = item.mobile;
                visitView.IsAppointment = item.isAppointment;
                visitArray.Add(visitView);
            }
            return visitArray;
        }

        public VisitModelView GetAppointment(string accessionNumber)
        {
            var appointment = (from v in entities.Visit_
                               from o in entities.Order_
                               from pp in entities.PatientProfile_
                               where v.OID_.Equals(o.Visit__OID_)
                               && pp.Patient__OID_.Equals(v.Patient__OID_)
                               && v.VisitNumberId_.Equals(accessionNumber)
                               select new
                               {
                                   idDocumentNumber = pp.IdDocumentNumber_,
                                   givenName = pp.GivenName_,
                                   middleName = pp.MiddleName_,
                                   familyName = pp.FamilyName_,
                                   birthDate = pp.DateOfBirth_,
                                   sex = pp.SexEnum__Code_,
                                   vipIndicator = pp.VipPatient_,
                                   telephone = pp.PatientProfileTelephoneNumber_.Where(x => x.PatientProfile__OID_.Equals(pp.OID_) && x.TelephoneEquipmentEnum__Code_.Equals("PH")).FirstOrDefault().Number_,
                                   mobilePhone = pp.PatientProfileTelephoneNumber_.Where(x => x.PatientProfile__OID_.Equals(pp.OID_) && x.TelephoneEquipmentEnum__Code_.Equals("CP")).FirstOrDefault().Number_,
                                   email = pp.PatientProfileEmailAddress_.Where(x => x.PatientProfile__OID_.Equals(pp.OID_)).FirstOrDefault().Address_,
                                   admitTime = v.AdmitTime_,
                                   dischargeTime = v.DischargeTime_,
                                   MrnId = pp.MrnId_,
                                   ReasonOfVisit = o.ReasonForStudy_,
                                   patientType = pp.PatientTypeEnum_.Value_,
                                   isAppointment = v.IsAppointment_
                               }).FirstOrDefault();

            VisitModelView visit = new VisitModelView();
            visit.IdDocumentNumber = appointment.idDocumentNumber;
            visit.GivenName = appointment.givenName;
            visit.MiddleName = appointment.middleName;
            visit.FamilyName = appointment.familyName;
            visit.DateOfBirth = (DateTime)appointment.birthDate;
            visit.Sex = appointment.sex;
            visit.VipIndicator = (bool)appointment.vipIndicator;
            visit.Telephone = appointment.telephone;
            visit.MobileNumber = appointment.mobilePhone;
            visit.Email = appointment.email;
            visit.AdmitTime = (DateTime)appointment.admitTime;
            visit.DischargeTime = (DateTime)appointment.dischargeTime;
            visit.MrnID = appointment.MrnId;
            visit.ReasonForStudy = appointment.ReasonOfVisit;
            visit.PatientType = appointment.patientType;
            visit.IsAppointment = appointment.isAppointment;
            return visit;
        }
    }
}
